﻿using Common.Contract;
using Common.Contract.Authentication;
using Common.Contract.Authentication.Record;
using Common.Contract.Authentication.Request;
using Common.Contract.Authentication.Response;
using Common.Contract.Paging;
using Common.Contract.SystemConfig.Record;
using Common.Data;
using Common.Data.Repository.Enum;
using Common.Service;
using Common.Service.DataTables;
using Common.Type;
using Common.Util;
using SMECustomerWebsite.Core.Configuration;
using SMECustomerWebsite.Filters;
using SMECustomerWebsite.Models.ViewModels.CloseDao;
using SMECustomerWebsite.Models.ViewModels.SaleCode;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SMECustomerWebsite.Controllers
{
    public class SaleCodeController : ControllerBase
    {
        #region constant string

        public const string PrefixCloseDaoId = "CLD";
        public const string PrefixEditDaoId = "EDD";
        #endregion
        #region Close Dao

        [Authorize]
        [CustomActionFilter]
        public ActionResult ListCloseDaoRequest(CloseDaoRequestViewModel vm)
        {
            vm.CurrentUser = CurrentUserRecord;
            return View(vm);
        }

        [Authorize]
        [CustomActionFilter]
        public ActionResult AddCloseDaoRequest(CloseDaoRequestViewModel vm = null)
        {
            if (vm == null || vm.CurrentUser == null)
            {
                vm = new CloseDaoRequestViewModel
                {
                    CurrentUser = CurrentUserRecord
                };
            }
            return View(vm);
        }

        [HttpPost]
        [Authorize]
        public ActionResult AddCloseDaoRequestByInput(CloseDaoRequestViewModel vm)
        {
            CloseDaoRequestViewModel model = new CloseDaoRequestViewModel();
            try
            {
                var listDao = vm.Dao;
                List<CloseDaoRequestRecord> listSaleCode = new List<CloseDaoRequestRecord>();
                listDao.ForEach(x =>
                {
                    listSaleCode.Add(new CloseDaoRequestRecord
                    {
                        Dao = x
                    });
                });
                using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                {
                    ResponseRecord response = null;
                    UpdateCloseDaoRequestRequest request = new UpdateCloseDaoRequestRequest
                    {
                        Header = new RequestHeaderRecord
                        {
                            ApplicationKey = SystemConfiguration.ApplicationKey,
                            CallerName = "SMEsCustomer360Degree.Controllers.AdminChecklistController.UpdateRule"
                        },
                        ListCloseDaoRequest = listSaleCode,
                        CurrentUser = CurrentUserRecord
                    };
                    response = serviceClient.Proxy.AddListCloseDaoRequest(request);
                    bool isUpdate = response.IsSuccess;
                    if (!isUpdate)
                    {
                        string cookieName = CurrentUserRecord.UserName + "CLDError";
                        CreateCookie(cookieName, response.ErrorMessage);
                        return RedirectToAction("AddCloseDaoRequest", "SaleCode");
                    }
                    else
                    {
                        string cookieName = CurrentUserRecord.UserName + "CLDSuccess";
                        CreateCookie(cookieName, "Create request successfully");
                    }
                }
            }
            catch (Exception ex)
            {
                string cookieName = CurrentUserRecord.UserName + "CLDError";
                CreateCookie(cookieName, ex.Message);
                return RedirectToAction("AddCloseDaoRequest", "SaleCode");
            }
            return RedirectToAction("ListCloseDaoRequest", "SaleCode");
        }
        #endregion

        #region Change Dao Info

        [Authorize]
        [CustomActionFilter]
        public ActionResult ListEditDaoRequest(EditDaoRequestViewModel vm)
        {
            vm.CurrentUser = CurrentUserRecord;
            return View(vm);
        }

        [Authorize]
        [CustomActionFilter]
        public ActionResult AddEditDaoRequest(EditDaoRequestViewModel vm = null)
        {
            if (vm == null || vm.CurrentUser == null)
            {
                vm = new EditDaoRequestViewModel
                {
                    CurrentUser = CurrentUserRecord
                };
            }
            return View(vm);
        }

        [HttpPost]
        [Authorize]
        public ActionResult AddEditDaoRequestByInput(EditDaoRequestViewModel vm)
        {
            bool isUpdate = false;
            string errorMess = string.Empty;
            try
            {
                string fName = "";
                if (ModelState.IsValid)
                {
                    HttpPostedFileBase file = vm.File;
                    //Save file content goes here
                    if (file != null && file.ContentLength > 0)
                    {
                        fName = file.FileName;
                        if (ALLOW_FILE_DAO_MANAGEMENT.Contains(Path.GetExtension(fName).ToLower()))
                        {
                            var originalDirectory = new DirectoryInfo(string.Format("{0}File/EditDao/OfferLetter/{1}/{2}", Server.MapPath(@"\"), DateTime.Now.Year, DateTime.Now.Month));
                            string linkFileLocation = UploadFile(originalDirectory, file);

                            var linkFile = string.Format("/File/EditDao/OfferLetter/{0}/{1}/{2}", DateTime.Now.Year, DateTime.Now.Month, file.FileName);
                            EditDaoRequestRecord saleCode = new EditDaoRequestRecord
                            {
                                Dao = vm.Dao,
                                FullName = vm.DaoName,
                                Cif = vm.Cif,
                                StaffId = vm.IdMis,
                                DeptParent = vm.Branch,
                                PositionName = vm.DeliveryPoint,
                                PathOfferLetter = linkFile,
                            };
                            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                            {
                                ResponseRecord response = null;
                                UpdateEditDaoRequestRequest request = new UpdateEditDaoRequestRequest
                                {
                                    Header = new RequestHeaderRecord
                                    {
                                        ApplicationKey = SystemConfiguration.ApplicationKey,
                                        CallerName = "SMEsCustomer360Degree.Controllers.AdminChecklistController.UpdateRule"
                                    },
                                    Record = saleCode,
                                    CurrentUser = CurrentUserRecord
                                };
                                response = serviceClient.Proxy.AddEditDaoRequest(request);
                                isUpdate = response.IsSuccess;
                                errorMess = response.ErrorMessage;
                            }
                        }
                        else
                        {
                            isUpdate = false;
                            errorMess = "File sai định dạng";
                        }
                    }
                    else
                    {
                        isUpdate = false;
                        errorMess = "Nhập scan hoặc ảnh chụp quyết định thay đổi thông tin";
                    }
                }
                else
                {
                    isUpdate = false;
                    errorMess = "Nhập scan hoặc ảnh chụp quyết định thay đổi thông tin";
                }
            }
            catch (Exception ex)
            {
                string cookieName = CurrentUserRecord.UserName + "EDDError";
                CreateCookie(cookieName, ex.Message);
                return RedirectToAction("AddEditDaoRequest", "SaleCode");
            }
            if (!isUpdate)
            {
                string cookieName = CurrentUserRecord.UserName + "EDDError";
                CreateCookie(cookieName, errorMess);
                return RedirectToAction("AddEditDaoRequest", "SaleCode");
            }
            else
            {
                string cookieName = CurrentUserRecord.UserName + "EDDSuccess";
                CreateCookie(cookieName, "Create request successfully");
            }
            return RedirectToAction("ListEditDaoRequest", "SaleCode");
        }
        #endregion

        #region Ajax Method
        [Authorize]
        [HttpPost]
        public ActionResult ListCloseDaoRequest(DataTablesPageRequest pageRequest)
        {
            DataTableResponse pageResponse = null;
            var customerRecords = new RetrieveListCloseDaoRequestResponse();
            List<object[]> listCust = new List<object[]>();
            FilterRecord filter = GetBaseFilter(pageRequest.SearchColumns);
            switch (CurrentUserRecord.GroupIdentifier)
            {
                case "1":
                    filter.ContractType = pageRequest.SearchColumns[4];
                    filter.Email = pageRequest.SearchColumns[5];
                    filter.CusOpenDate = pageRequest.SearchColumns[6];
                    break;
                case "2":
                    filter.ContractType = pageRequest.SearchColumns[3];
                    filter.Email = pageRequest.SearchColumns[4];
                    filter.CusOpenDate = pageRequest.SearchColumns[5];
                    break;
                case "3":
                    if (CurrentUserRecord.Position == "HUB Manager")
                    {
                        filter.ContractType = pageRequest.SearchColumns[3];
                        filter.Email = pageRequest.SearchColumns[4];
                        filter.CusOpenDate = pageRequest.SearchColumns[5];
                    }
                    else
                    {
                        filter.ContractType = pageRequest.SearchColumns[2];
                        filter.Email = pageRequest.SearchColumns[3];
                        filter.CusOpenDate = pageRequest.SearchColumns[4];
                    }
                    break;
                default:
                    break;
            }
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {

                RetrieveListCloseDaoRequestRequest request = new RetrieveListCloseDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManagerController.RetrieveListCreateDaoRequest"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest == null ? 0 : pageRequest.DisplayLength,
                        PageIndex = pageRequest == null ? 0 : pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    Sort = new SortRecord
                    {
                        SortDir = pageRequest.SortDir
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter
                };
                customerRecords = serviceClient.Proxy.RetrieveListCloseDaoRequest(request);
            }
            var resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<CloseDaoRequestRecord>() : customerRecords.Records;
            if (resultCustomer.Count > 0)
            {
                switch (CurrentUserRecord.GroupIdentifier)
                {
                    case "1":
                        listCust = resultCustomer.Select(x => new object[]{
                                                        x.Zone,
                                                        x.Branch,
                                                        string.Format("{0}{1}",PrefixCloseDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusCloseDaoEnum>.GetDisplayValue((StatusCloseDaoEnum)x.Status),
                                                        x.Dao,
                                                        x.CreatedDate.ToString("dd/MM/yyyy"),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.PathOfferLetter,
                                                        x.NeedUploadOfferLetter
                        }).ToList();
                        break;
                    case "2":
                        listCust = resultCustomer.Select(x => new object[]{
                                                        x.Branch,
                                                        string.Format("{0}{1}",PrefixCloseDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusCloseDaoEnum>.GetDisplayValue((StatusCloseDaoEnum)x.Status),
                                                        x.Dao,
                                                        x.CreatedDate.ToString("dd/MM/yyyy"),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.PathOfferLetter,
                                                        x.NeedUploadOfferLetter
                        }).ToList();
                        break;
                    case "3":
                        if (CurrentUserRecord.Position.Equals("Hub Manager"))
                        {
                            listCust = resultCustomer.Select(x => new object[]{
                                                        string.Format("{0}{1}",PrefixCloseDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusCloseDaoEnum>.GetDisplayValue((StatusCloseDaoEnum)x.Status),
                                                        x.Dao,
                                                        x.CreatedDate.ToString("dd/MM/yyyy"),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.PathOfferLetter,
                                                        x.NeedUploadOfferLetter
                        }).ToList();
                        }
                        else
                        {
                            listCust = resultCustomer.Select(x => new object[]{
                                                        string.Format("{0}{1}",PrefixCloseDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusCloseDaoEnum>.GetDisplayValue((StatusCloseDaoEnum)x.Status),
                                                        x.Dao,
                                                        x.CreatedDate.ToString("dd/MM/yyyy"),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.PathOfferLetter,
                                                        x.NeedUploadOfferLetter
                        }).ToList();
                        }
                        break;
                    case "4":
                        listCust = resultCustomer.Select(x => new object[]{
                                                        string.Format("{0}{1}",PrefixCloseDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusCloseDaoEnum>.GetDisplayValue((StatusCloseDaoEnum)x.Status),
                                                        x.Dao,
                                                        x.CreatedDate.ToString("dd/MM/yyyy"),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.PathOfferLetter,
                                                        x.NeedUploadOfferLetter
                        }).ToList();
                        break;
                    case "6":
                        listCust = resultCustomer.Select(x => new object[]{
                                                        string.Format("{0}{1}",PrefixCloseDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusCloseDaoEnum>.GetDisplayValue((StatusCloseDaoEnum)x.Status),
                                                        x.Dao,
                                                        x.CreatedDate.ToString("dd/MM/yyyy"),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.PathOfferLetter,
                                                        x.NeedUploadOfferLetter
                        }).ToList();
                        break;
                    default:
                        break;
                }
            }
            pageResponse = new DataTableResponse
            {
                sEcho = pageRequest.Echo,
                iTotalRecords = customerRecords.Page.TotalRecords,
                sColumns = pageRequest.ColumnNames,
                aaData = listCust
            };
            return Json(pageResponse);
        }

        [HttpPost]
        [Authorize]
        public ActionResult GetListAllDaoCode(string searchText)
        {
            List<SaleCodeInfoRecord> resultCustomer = new List<SaleCodeInfoRecord>();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                FilterRecord filter = new FilterRecord
                {
                    TextSearchByCif = searchText
                };
                RetrieveListSaleCodeRequest request = new RetrieveListSaleCodeRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.RepreInfo"
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter
                };
                var customerRecords = new RetrieveListSaleCodeResponse();
                customerRecords = serviceClient.Proxy.RetrieveListSaleCode(request);
                resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<SaleCodeInfoRecord>() : customerRecords.Records;
            }
            var objectItem = resultCustomer.Select(x => new
            {
                id = x.Dao,
                text = x.Dao,
                daoName = x.DaoName,
                staffId = x.StaffId,
                cif = x.Cif,
                deliveryPoint = x.DeliveryPoint,
                depParent = x.DeptParent
            });
            return Json(objectItem);
        }

        [HttpPost]
        [Authorize]
        public ActionResult ApproveCloseDaoRequest(int request)
        {
            CloseDaoRequestRecord userRequest = new CloseDaoRequestRecord
            {
                Id = request,
                Status = (int)StatusCloseDaoEnum.Approve
            };
            var result = UpdateCloseDaoStatus(userRequest);
            return Json(result);
        }

        [HttpPost]
        [Authorize]
        public ActionResult RejectCloseDaoRequest(int request)
        {
            CloseDaoRequestRecord userRequest = new CloseDaoRequestRecord
            {
                Id = request,
                Status = (int)StatusCloseDaoEnum.Reject,
                RejectPerson = CurrentUserRecord.UserName
            };
            var result = UpdateCloseDaoStatus(userRequest);
            return Json(result);
        }

        [HttpPost]
        [Authorize]
        public ActionResult RejectReasonCloseDaoRequest(CloseDaoRequestViewModel model)
        {
            CloseDaoRequestRecord userRequest = new CloseDaoRequestRecord
            {
                Id = model.RequestId,
                Status = (int)StatusCloseDaoEnum.Reject,
                RejectReason = model.RejectReason,
                RejectPerson = CurrentUserRecord.UserName
            };
            var result = UpdateCloseDaoStatus(userRequest);
            if (!result.IsSuccess)
            {
                string cookieName = CurrentUserRecord.UserName + "CLDError";
                CreateCookie(cookieName, result.ErrorMessage);
            }
            else
            {
                string cookieName = CurrentUserRecord.UserName + "CLDSuccess";
                CreateCookie(cookieName, "Reject request successfully");
            }
            return RedirectToAction("ListCloseDaoRequest", "SaleCode");
        }
        [HttpPost]
        [Authorize]
        public ActionResult CloseDaoInfo(string id)
        {
            int RequestId = int.Parse(id);
            CloseDaoRequestRecord resultCustomer = new CloseDaoRequestRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                RetrieveCloseDaoInfoRequest request = new RetrieveCloseDaoInfoRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.CustomerInfo"
                    },
                    CurrentUser = CurrentUserRecord,
                    RequestId = RequestId
                };
                var customerRecords = new RetrieveCloseDaoInfoResponse();
                customerRecords = serviceClient.Proxy.RetrieveCloseDaoInfoById(request);
                resultCustomer = (customerRecords == null || customerRecords.Record == null) ? new CloseDaoRequestRecord() : customerRecords.Record;
            }
            var objectItem = new
            {
                fullName = resultCustomer.FullName,
                position = resultCustomer.PositionName,
                staffId = resultCustomer.StaffId,
                email = resultCustomer.Email,
                cif = resultCustomer.Cif,
                legalId = resultCustomer.LegalId,
                phone = resultCustomer.Phone,
                branch = resultCustomer.Branch,
                DAO = resultCustomer.Dao
            };
            return Json(objectItem);
        }

        [HttpPost]
        [Authorize]
        public ActionResult ExportDataCloseDaoRequestToIT()
        {
            FilterRecord filter = new FilterRecord
            {
                IsExport = true
            };
            RetrieveListCloseDaoRequestResponse result = new RetrieveListCloseDaoRequestResponse();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {

                RetrieveListCloseDaoRequestRequest request = new RetrieveListCloseDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManagerController.RetrieveListCreateDaoRequest"
                    },
                    Page = new PageRecord
                    {
                        PageSize = 0,
                        PageIndex = 0
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter
                };
                result = serviceClient.Proxy.RetrieveListCloseDaoRequestForExport(request);
            }
            var resultCustomer = (result == null || result.Records == null) ? new List<ExportCloseDaoRequestViewModel>() : result.Records.Select(x => new ExportCloseDaoRequestViewModel
            {
                Dao = x.Dao,
                Area = x.Branch,
                Name = x.FullName,
                Delivery = x.PositionName,
                Level = x.Level,
                DeparmentParent = x.BranchId.Substring(x.BranchId.Length - 3),
                StaffId = x.StaffId,
                Cif = x.Cif,
                FromDate = x.FromDate,
                ToDate = string.Empty,
                Id = x.Id.ToString()
            }).ToList();
            DataTable dt = new DataTable();
            dt.TableName = "Request Closing Dao ";
            var fileName = "Request Closing Dao " + DateTime.Now.ToShortDateString() + ".xlsx";

            fileName = fileName.Replace("/", "");
            dt = ToDataTable(resultCustomer);
            ExportToExcel(dt, fileName);
            bool isSucces = UpdateStatusListCloseDaoRequest(result.Records, (int)StatusCloseDaoEnum.ITProcessing);
            CloseDaoRequestViewModel vm = new CloseDaoRequestViewModel();
            if (!isSucces)
            {
                vm.MessageType = MessageType.Error;
                vm.Message = "Có lỗi xảy ra, vui lòng thử lại";
            }
            else
            {
                vm.MessageType = MessageType.Success;
                vm.Message = "Cập nhật thành công!";
            }
            return RedirectToAction("ListCloseDaoRequest", "SaleCode", vm);
        }

        [Authorize]
        [HttpPost]
        public ActionResult ImportResultCloseDaoRequest(FormCollection formCollection)
        {
            CloseDaoRequestViewModel vm = new CloseDaoRequestViewModel();
            if (Request != null)
            {
                HttpPostedFileBase file = Request.Files["UploadedFile"];

                if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                {
                    string now = DateTime.Now.ConvertToTimestamp().ToString();
                    string fileExtension = Path.GetExtension(file.FileName);
                    string fileName = string.Format("BIC_EDDAO_{0}_{1}{2}", CurrentUserRecord.UserName, now, fileExtension);
                    if (fileExtension == ".xls" || fileExtension == ".xlsx")
                    {
                        var originalDirectory = new DirectoryInfo(Server.MapPath("~/File/OfferLetter/"));
                        string fileLocation = UploadFile(originalDirectory, file, fileName);

                        DataTable dt = ConvertXSLXtoDataTable(fileLocation, fileExtension);
                        List<CloseDaoRequestRecord> listRequest = new List<CloseDaoRequestRecord>();
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            var item = dt.Rows[i];
                            CloseDaoRequestRecord record = new CloseDaoRequestRecord
                            {
                                Id = int.Parse(item[10].ToString()),
                                Status = (int)StatusChangeDaoEnum.Done
                            };
                            listRequest.Add(record);
                        }

                        bool isSucces = UpdateStatusListCloseDaoRequest(listRequest, (int)StatusCloseDaoEnum.Done);
                        if (!isSucces)
                        {
                            System.IO.File.Delete(fileLocation);
                            vm.MessageType = MessageType.Error;
                            vm.Message = "Có lỗi xảy ra, vui lòng thử lại";
                        }
                        else
                        {
                            vm.MessageType = MessageType.Success;
                            vm.Message = "Cập nhật thành công!";
                        }
                    }
                }
            }
            return RedirectToAction("ListCloseDaoRequest", "SaleCode", vm);
        }


        [Authorize]
        [HttpPost]
        public ActionResult UploadOfferLetter(CloseDaoRequestViewModel vm)
        {
            CloseDaoRequestViewModel model = new CloseDaoRequestViewModel();
            model.CurrentUser = CurrentUserRecord;
            try
            {
                HttpPostedFileBase file = vm.File;
                //Save file content goes here
                if (file != null && file.ContentLength > 0)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        var fName = file.FileName;
                        var originalDirectory = new DirectoryInfo(string.Format("{0}File/OfferLetter/CloseDao/{1}/{2}", Server.MapPath(@"\"), DateTime.Now.Year, DateTime.Now.Month));
                        string linkFileLocation = UploadFile(originalDirectory, file);

                        var linkFile = string.Format("/File/OfferLetter/CloseDao/{0}/{1}/{2}", DateTime.Now.Year, DateTime.Now.Month, file.FileName);

                        using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                        {
                            ResponseRecord response = null;

                            CloseDaoRequestRecord userRequest = new CloseDaoRequestRecord
                            {
                                Id = vm.RequestId,
                                PathOfferLetter = linkFile
                            };
                            UpdateCloseDaoRequestRequest request = new UpdateCloseDaoRequestRequest
                            {
                                Header = new RequestHeaderRecord
                                {
                                    ApplicationKey = SystemConfiguration.ApplicationKey,
                                    CallerName = "SMEsCustomer360Degree.Controllers.AdminChecklistController.UpdateRule"
                                },
                                CurrentUser = CurrentUserRecord,
                                Record = userRequest
                            };
                            response = serviceClient.Proxy.UploadOfferLetterCloseDao(request);

                            if (!response.IsSuccess)
                            {
                                string cookieName = CurrentUserRecord.UserName + "CLDError";
                                CreateCookie(cookieName, response.ErrorMessage);
                            }
                            else
                            {
                                string cookieName = CurrentUserRecord.UserName + "CLDSuccess";
                                CreateCookie(cookieName, "Upload successfully");
                            }
                        }
                    }
                    else
                    {
                        string cookieName = CurrentUserRecord.UserName + "CLDError";
                        CreateCookie(cookieName, "File sai định dạng");
                    }
                }
            }
            catch (Exception ex)
            {
                string cookieName = CurrentUserRecord.UserName + "CLDError";
                CreateCookie(cookieName, ex.Message);
            }
            return RedirectToAction("ListCloseDaoRequest", "SaleCode", model);
        }

        #endregion

        #region Edit Dao Ajax method
        [Authorize]
        [HttpPost]
        public ActionResult EditDaoInfo(string id)
        {
            int RequestId = int.Parse(id);
            CloseDaoRequestRecord resultCustomer = new CloseDaoRequestRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                RetrieveCloseDaoInfoRequest request = new RetrieveCloseDaoInfoRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.CustomerInfo"
                    },
                    CurrentUser = CurrentUserRecord,
                    RequestId = RequestId
                };
                var customerRecords = new RetrieveCloseDaoInfoResponse();
                customerRecords = serviceClient.Proxy.RetrieveCloseDaoInfoById(request);
                resultCustomer = (customerRecords == null || customerRecords.Record == null) ? new CloseDaoRequestRecord() : customerRecords.Record;
            }
            var objectItem = new
            {
                fullName = resultCustomer.FullName,
                position = resultCustomer.PositionName,
                staffId = resultCustomer.StaffId,
                email = resultCustomer.Email,
                cif = resultCustomer.Cif,
                legalId = resultCustomer.LegalId,
                phone = resultCustomer.Phone,
                branch = resultCustomer.Branch,
                DAO = resultCustomer.Dao
            };
            return Json(objectItem);
        }
        [Authorize]
        [HttpPost]
        public ActionResult EditDaoRequestInfoData(DataTablesPageRequest pageRequest, string requestId)
        {
            DataTableResponse pageResponse = null;
            int RequestId = int.Parse(requestId);
            var customerRecords = new RetrieveEditDaoRequestDetailResponse();
            List<object[]> listCust = new List<object[]>();
            FilterRecord filter = new FilterRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {

                RetrieveEditDaoRequestDetailRequest request = new RetrieveEditDaoRequestDetailRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManagerController.RetrieveListCreateDaoRequest"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest == null ? 0 : pageRequest.DisplayLength,
                        PageIndex = pageRequest == null ? 0 : pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter,
                    RequestId = RequestId
                };
                customerRecords = serviceClient.Proxy.RetrieveEditDaoRequestDetail(request);
            }
            var resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<EditDaoRequestDetailRecord>() : customerRecords.Records;
            if (resultCustomer.Count > 0)
            {
                listCust = resultCustomer.Select(x => new object[]{
                                                        x.Dao,
                                                        x.DaoName,
                                                        x.Division,
                                                        x.DeptParent,
                                                        x.PositionName,
                                                        x.StaffId,
                                                        x.Cif,
                                                        x.Type
                        }).ToList();
            }
            pageResponse = new DataTableResponse
            {
                sEcho = pageRequest.Echo,
                iTotalRecords = customerRecords.Page.TotalRecords,
                sColumns = pageRequest.ColumnNames,
                aaData = listCust
            };
            return Json(pageResponse);
        }

        [Authorize]
        [HttpPost]
        public ActionResult ListEditDaoRequestData(DataTablesPageRequest pageRequest)
        {
            DataTableResponse pageResponse = null;
            var customerRecords = new RetrieveEditDaoRequestResponse();
            List<object[]> listCust = new List<object[]>();
            FilterRecord filter = GetBaseFilter(pageRequest.SearchColumns);
            switch (CurrentUserRecord.GroupIdentifier)
            {
                case "1":
                    filter.ContractType = pageRequest.SearchColumns[4];
                    filter.Email = pageRequest.SearchColumns[5];
                    filter.CusOpenDate = pageRequest.SearchColumns[6];
                    break;
                case "2":
                    filter.ContractType = pageRequest.SearchColumns[3];
                    filter.Email = pageRequest.SearchColumns[4];
                    filter.CusOpenDate = pageRequest.SearchColumns[5];
                    break;
                case "3":
                    if (CurrentUserRecord.Position == "HUB Manager")
                    {
                        filter.ContractType = pageRequest.SearchColumns[3];
                        filter.Email = pageRequest.SearchColumns[4];
                        filter.CusOpenDate = pageRequest.SearchColumns[5];
                    }
                    else
                    {
                        filter.ContractType = pageRequest.SearchColumns[2];
                        filter.Email = pageRequest.SearchColumns[3];
                        filter.CusOpenDate = pageRequest.SearchColumns[4];
                    }
                    break;
                default:
                    break;
            }
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {

                RetrieveEditDaoRequestRequest request = new RetrieveEditDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManagerController.RetrieveListCreateDaoRequest"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest == null ? 0 : pageRequest.DisplayLength,
                        PageIndex = pageRequest == null ? 0 : pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    Sort = new SortRecord
                    {
                        SortDir = pageRequest.SortDir
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter
                };
                customerRecords = serviceClient.Proxy.RetrieveEditDaoRequest(request);
            }
            var resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<EditDaoRequestRecord>() : customerRecords.Records;
            if (resultCustomer.Count > 0)
            {
                switch (CurrentUserRecord.GroupIdentifier)
                {
                    case "1":
                        listCust = resultCustomer.Select(x => new object[]{
                                                        x.Zone,
                                                        x.Branch,
                                                        string.Format("{0}{1}",PrefixEditDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusCloseDaoEnum>.GetDisplayValue((StatusCloseDaoEnum)x.Status),
                                                        x.Dao,
                                                        x.CreatedDate.ToString("dd/MM/yyyy"),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.PathOfferLetter,
                                                        x.NeedUploadOfferLetter
                        }).ToList();
                        break;
                    case "2":
                        listCust = resultCustomer.Select(x => new object[]{
                                                        x.Branch,
                                                        string.Format("{0}{1}",PrefixEditDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusCloseDaoEnum>.GetDisplayValue((StatusCloseDaoEnum)x.Status),
                                                        x.Dao,
                                                        x.CreatedDate.ToString("dd/MM/yyyy"),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.PathOfferLetter,
                                                        x.NeedUploadOfferLetter
                        }).ToList();
                        break;
                    case "3":
                        if (CurrentUserRecord.Position.Equals("Hub Manager"))
                        {
                            listCust = resultCustomer.Select(x => new object[]{
                                                        string.Format("{0}{1}",PrefixEditDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusCloseDaoEnum>.GetDisplayValue((StatusCloseDaoEnum)x.Status),
                                                        x.Dao,
                                                        x.CreatedDate.ToString("dd/MM/yyyy"),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.PathOfferLetter,
                                                        x.NeedUploadOfferLetter
                        }).ToList();
                        }
                        else
                        {
                            listCust = resultCustomer.Select(x => new object[]{
                                                        string.Format("{0}{1}",PrefixEditDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusCloseDaoEnum>.GetDisplayValue((StatusCloseDaoEnum)x.Status),
                                                        x.Dao,
                                                        x.CreatedDate.ToString("dd/MM/yyyy"),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.PathOfferLetter,
                                                        x.NeedUploadOfferLetter
                        }).ToList();
                        }
                        break;
                    case "4":
                        listCust = resultCustomer.Select(x => new object[]{
                                                        string.Format("{0}{1}",PrefixEditDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusCloseDaoEnum>.GetDisplayValue((StatusCloseDaoEnum)x.Status),
                                                        x.Dao,
                                                        x.CreatedDate.ToString("dd/MM/yyyy"),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.PathOfferLetter,
                                                        x.NeedUploadOfferLetter
                        }).ToList();
                        break;
                    case "6":
                        listCust = resultCustomer.Select(x => new object[]{
                                                        string.Format("{0}{1}",PrefixEditDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusCloseDaoEnum>.GetDisplayValue((StatusCloseDaoEnum)x.Status),
                                                        x.Dao,
                                                        x.CreatedDate.ToString("dd/MM/yyyy"),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.PathOfferLetter,
                                                        x.NeedUploadOfferLetter
                        }).ToList();
                        break;
                    default:
                        break;
                }
            }
            pageResponse = new DataTableResponse
            {
                sEcho = pageRequest.Echo,
                iTotalRecords = customerRecords.Page.TotalRecords,
                sColumns = pageRequest.ColumnNames,
                aaData = listCust
            };
            return Json(pageResponse);
        }

        [HttpPost]
        [Authorize]
        public ActionResult ApproveEditDaoRequest(int request)
        {
            EditDaoRequestRecord userRequest = new EditDaoRequestRecord
            {
                Id = request,
                Status = (int)StatusCloseDaoEnum.Approve
            };
            var result = UpdateEditDaoStatus(userRequest);
            return Json(result);
        }

        [HttpPost]
        [Authorize]
        public ActionResult RejectEditDaoRequest(int request)
        {
            EditDaoRequestRecord userRequest = new EditDaoRequestRecord
            {
                Id = request,
                Status = (int)StatusCloseDaoEnum.Reject,
                RejectPerson = CurrentUserRecord.UserName
            };
            var result = UpdateEditDaoStatus(userRequest);
            return Json(result);
        }

        [HttpPost]
        [Authorize]
        public ActionResult RejectReasonEditDaoRequest(EditDaoRequestViewModel model)
        {
            EditDaoRequestRecord userRequest = new EditDaoRequestRecord
            {
                Id = model.RequestId,
                Status = (int)StatusCloseDaoEnum.Reject,
                RejectReason = model.RejectReason,
                RejectPerson = CurrentUserRecord.UserName
            };
            var result = UpdateEditDaoStatus(userRequest);
            if (!result.IsSuccess)
            {
                string cookieName = CurrentUserRecord.UserName + "EDDError";
                CreateCookie(cookieName, result.ErrorMessage);
            }
            else
            {
                string cookieName = CurrentUserRecord.UserName + "EDDSuccess";
                CreateCookie(cookieName, "Reject request successfully");
            }
            return RedirectToAction("ListEditDaoRequest", "SaleCode");
        }

        [Authorize]
        [HttpPost]
        public ActionResult ImportResultEditDaoRequest(FormCollection formCollection)
        {
            EditDaoRequestViewModel vm = new EditDaoRequestViewModel();
            if (Request != null)
            {
                HttpPostedFileBase file = Request.Files["UploadedFile"];

                if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                {
                    string now = DateTime.Now.ConvertToTimestamp().ToString();
                    string fileExtension = Path.GetExtension(file.FileName);
                    string fileName = string.Format("BIC_EDDAO_{0}_{1}{2}", CurrentUserRecord.UserName, now, fileExtension);
                    if (fileExtension == ".xls" || fileExtension == ".xlsx")
                    {
                        var originalDirectory = new DirectoryInfo(Server.MapPath("~/File/OfferLetter/"));
                        string fileLocation = UploadFile(originalDirectory, file, fileName);

                        DataTable dt = ConvertXSLXtoDataTable(fileLocation, fileExtension);
                        List<EditDaoRequestRecord> listRequest = new List<EditDaoRequestRecord>();
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            var item = dt.Rows[i];
                            EditDaoRequestRecord record = new EditDaoRequestRecord
                            {
                                Id = int.Parse(item[0].ToString()),
                                Status = (int)StatusChangeDaoEnum.Done
                            };
                            listRequest.Add(record);
                        }

                        bool isSucces = UpdateStatusListEditDaoRequest(listRequest, (int)StatusCloseDaoEnum.Done);
                        if (!isSucces)
                        {
                            System.IO.File.Delete(fileLocation);
                            vm.MessageType = MessageType.Error;
                            vm.Message = "Có lỗi xảy ra, vui lòng thử lại";
                        }
                        else
                        {
                            vm.MessageType = MessageType.Success;
                            vm.Message = "Cập nhật thành công!";
                        }
                    }
                }
            }
            return RedirectToAction("ListEditDaoRequest", "SaleCode", vm);
        }


        [HttpPost]
        [Authorize]
        public ActionResult ExportDataEditDaoRequestToIT()
        {
            FilterRecord filter = new FilterRecord
            {
                IsExport = true
            };
            RetrieveEditDaoRequestForExelResponse result = new RetrieveEditDaoRequestForExelResponse();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {

                RetrieveEditDaoRequestRequest request = new RetrieveEditDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManagerController.RetrieveListCreateDaoRequest"
                    },
                    Page = new PageRecord
                    {
                        PageSize = 0,
                        PageIndex = 0
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter
                };
                result = serviceClient.Proxy.RetrieveListEditDaoRequestForExport(request);
            }
            var resultCustomer = (result == null || result.Records == null) ? new List<ExportEditDaoRequestViewModel>() : result.Records.Select(x => new ExportEditDaoRequestViewModel
            {
                RequestId = x.RequestId,
                Dao = x.Dao,
                OldDaoName = x.OldDaoName,
                OldDivision = x.OldDivision,
                OldPositionName = x.OldPositionName,
                OldDeptParent = x.OldDeptParent,
                OldStaffId = x.OldStaffId,
                OldCif = x.OldCif,
                OldFromDate = x.OldFromDate,
                NewDaoName = x.NewDaoName,
                NewDivision = x.NewDivision,
                NewPositionName = x.NewPositionName,
                NewDeptParent = x.NewDeptParent,
                NewStaffId = x.NewStaffId,
                NewCif = x.NewCif,
                NewFromDate = x.NewFromDate,
            }).ToList();
            DataTable dt = new DataTable();
            dt.TableName = "Request Editting Dao ";
            var fileName = "Request Editting Dao " + DateTime.Now.ToShortDateString() + ".xlsx";

            fileName = fileName.Replace("/", "");
            dt = ToDataTable(resultCustomer);
            ExportToExcel(dt, fileName);
            var updateStatusRequest = result.Records.Select(x => new EditDaoRequestRecord
            {
                Id = x.RequestId
            }).ToList();
            bool isSucces = UpdateStatusListEditDaoRequest(updateStatusRequest, (int)StatusCloseDaoEnum.ITProcessing);
            EditDaoRequestViewModel vm = new EditDaoRequestViewModel();
            if (!isSucces)
            {
                vm.MessageType = MessageType.Error;
                vm.Message = "Có lỗi xảy ra, vui lòng thử lại";
            }
            else
            {
                vm.MessageType = MessageType.Success;
                vm.Message = "Cập nhật thành công!";
            }
            return RedirectToAction("ListEditDaoRequest", "SaleCode", vm);
        }
        private ResponseRecord UpdateEditDaoStatus(EditDaoRequestRecord request)
        {
            ResponseRecord result = new ResponseRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                UpdateEditDaoRequestRequest requestUpdate = new UpdateEditDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    Record = request,
                    CurrentUser = CurrentUserRecord
                };
                result = serviceClient.Proxy.UpdateStatusEditDao(requestUpdate);
            }
            return result;
        }
        private bool UpdateStatusListEditDaoRequest(List<EditDaoRequestRecord> listRequest, int status)
        {
            ResponseRecord result = new ResponseRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                listRequest.ForEach(x =>
                {
                    x.Status = status;
                });
                UpdateEditDaoRequestRequest requestUpdate = new UpdateEditDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    CurrentUser = CurrentUserRecord,
                    ListEditDaoRequest = listRequest
                };
                result = serviceClient.Proxy.UpdateStatusListEditDaoRequest(requestUpdate);
            }
            return result.IsSuccess;
        }

        #endregion

        #region Private Methods
        private bool UpdateStatusListCloseDaoRequest(List<CloseDaoRequestRecord> listRequest, int status)
        {
            ResponseRecord result = new ResponseRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                listRequest.ForEach(x =>
                {
                    x.Status = status;
                });
                UpdateCloseDaoRequestRequest requestUpdate = new UpdateCloseDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    CurrentUser = CurrentUserRecord,
                    ListCloseDaoRequest = listRequest
                };
                result = serviceClient.Proxy.UpdateStatusListCloseDaoRequest(requestUpdate);
            }
            return result.IsSuccess;
        }
        private ResponseRecord UpdateCloseDaoStatus(CloseDaoRequestRecord request)
        {
            ResponseRecord result = new ResponseRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                UpdateCloseDaoRequestRequest requestUpdate = new UpdateCloseDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    Record = request,
                    CurrentUser = CurrentUserRecord
                };
                result = serviceClient.Proxy.UpdateStatusCloseDao(requestUpdate);
            }
            return result;
        }
        #endregion

    }
}